<template>
  <PageWrapper title="专利申请趋势分析" contentFullHeight>
    <CollapseContainer title="查询条件">
      <BasicForm @register="registerForm" @submit="handleSubmit" @reset="handleReset" />
    </CollapseContainer>

    <CollapseContainer title="趋势图表" v-show="chartData.length > 0">
      <div class="chart-container">
        <div ref="chartRef" style="width: 100%; height: 600px"></div>
      </div>

      <!-- 统计信息 -->
      <a-row :gutter="16" class="statistics" v-if="statisticsData.length > 0">
        <a-col :span="6" v-for="stat in statisticsData" :key="stat.technologyId">
          <a-statistic :title="stat.technologyName" :value="stat.totalCount" :value-style="{ color: stat.color }">
            <template #suffix>件</template>
          </a-statistic>
        </a-col>
      </a-row>
    </CollapseContainer>

    <!-- 空状态 -->
    <div class="empty-state" v-show="!loading && chartData.length === 0">
      <a-empty description="请选择技术分类并点击加载数据" />
    </div>
  </PageWrapper>
</template>

<script lang="ts" name="patent-analysis-apply-trend-Index" setup>
  import { ref, onMounted, nextTick, computed, unref, type Ref } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { CollapseContainer } from '/@/components/Container';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useECharts } from '/@/hooks/web/useECharts';
  import type { EChartsOption } from 'echarts';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';

  import { getTechnologyTrend, getTechnologyTreeApi } from './TrendAnalysis.api';
  import type { TechnologyTrendData, TrendQueryResult, ChartSeries } from './TrendAnalysis.data';

  // JeecG 消息提示工具
  const { createMessage } = useMessage();

  // 响应式数据
  const loading = ref(false);
  const chartRef = ref<HTMLDivElement>();
  const chartData = ref<TechnologyTrendData[]>([]);

  // 年份选项（2010年到当前年份）
  const yearOptions = computed(() => {
    const currentYear = new Date().getFullYear();
    const options: Array<{ label: string; value: number }> = [];
    for (let year = 2010; year <= currentYear; year++) {
      options.push({ label: `${year}年`, value: year });
    }
    return options.reverse(); // 最新年份在前
  });

  // 表单配置 Schema
  const schemas: FormSchema[] = [
    {
      field: 'selectedTechnologies',
      component: 'ApiTreeSelect',
      label: '技术分类',
      required: false,
      componentProps: {
        api: getTechnologyTreeApi,
        resultField: 'result',  // 关键配置：指定从响应的 result 字段中获取数据
        multiple: true,         // ✅ 保留多选（对比多个技术分类）
        // ❌ 去掉 treeCheckable，不显示复选框（更简洁）
        placeholder: '请选择技术分类（可多选）',
        allowClear: true,
        showSearch: true,
        maxTagCount: 3,         // 最多显示 3 个标签
        dropdownStyle: { maxHeight: '400px', overflow: 'auto' },
        treeDefaultExpandAll: false,
        treeNodeFilterProp: 'title',
        // 🔑 字段映射配置 - 确保正确识别树节点结构
        fieldNames: {
          label: 'title',       // 显示文本字段
          value: 'key',         // 值字段
          children: 'children', // 子节点字段
        },
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: 'startYear',
      component: 'Select',
      label: '开始年份',
      defaultValue: 2010,
      componentProps: {
        placeholder: '开始年份',
        options: unref(yearOptions),
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: 'endYear',
      component: 'Select',
      label: '结束年份',
      defaultValue: new Date().getFullYear(),
      componentProps: {
        placeholder: '结束年份',
        options: unref(yearOptions),
      },
      colProps: {
        span: 6,
      },
    },
    {
      field: 'chartType',
      component: 'RadioButtonGroup',
      label: '图表类型',
      defaultValue: 'line',
      componentProps: {
        options: [
          { label: '折线图', value: 'line' },
          { label: '柱状图', value: 'bar' },
          { label: '混合图', value: 'mixed' },
        ],
      },
      colProps: {
        span: 8,
      },
    },
  ];

  // 使用 JeecG BasicForm
  const [registerForm, { getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    actionColOptions: {
      span: 4,
    },
    submitButtonOptions: {
      text: '加载数据',
      preIcon: 'ant-design:search-outlined',
    },
    resetButtonOptions: {
      text: '重置',
      preIcon: 'ant-design:reload-outlined',
    },
    showAdvancedButton: false,
    autoSubmitOnEnter: true,
  });

  // 统计数据
  const statisticsData = ref<
    Array<{
      technologyId: string;
      technologyName: string;
      totalCount: number;
      color: string;
    }>
  >([]);

  // 图表颜色配置
  const chartColors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16'];

  // 初始化图表
  const { setOptions: setChartOptions, getInstance: getChartInstance } = useECharts(chartRef as Ref<HTMLDivElement>);

  // 表单提交处理
  const handleSubmit = async (values: Recordable) => {
    console.log('表单提交数据:', values);

    const { selectedTechnologies, startYear, endYear, chartType } = values;

    // 🔧 确保 selectedTechnologies 是数组（处理单选和多选情况）
    let technologyIds: string[] = [];
    if (Array.isArray(selectedTechnologies)) {
      technologyIds = selectedTechnologies;
    } else if (selectedTechnologies) {
      // 如果是字符串，转换为数组
      technologyIds = [selectedTechnologies];
    }

    // 校验
    if (!technologyIds || technologyIds.length === 0) {
      createMessage.warning('请至少选择一个技术分类');
      return;
    }

    if (startYear > endYear) {
      createMessage.warning('开始年份不能大于结束年份');
      return;
    }

    loading.value = true;

    try {
      const params = {
        technologyIds: technologyIds,  // ✅ 确保发送的是数组
        startYear: startYear,
        endYear: endYear,
      };

      console.log('🚀 发送请求参数:', params);
      console.log('📊 技术分类ID数组:', technologyIds);

      const result: TrendQueryResult = await getTechnologyTrend(params);

      if (result && result.trendDataList) {
        chartData.value = result.trendDataList;
        // 保存 chartType 用于渲染
        currentChartType.value = chartType;
        generateStatistics();
        await nextTick();
        renderChart();
        createMessage.success(`成功加载 ${result.trendDataList.length} 个技术分类的趋势数据`);
      } else {
        chartData.value = [];
        createMessage.info('未查询到相关数据');
      }
    } catch (error: any) {
      console.error('查询趋势数据失败:', error);
      createMessage.error('查询失败：' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  };

  // 当前图表类型（用于渲染图表）
  const currentChartType = ref<'line' | 'bar' | 'mixed'>('line');

  // 生成统计数据
  const generateStatistics = () => {
    statisticsData.value = chartData.value.map((item, index) => ({
      technologyId: item.technologyId,
      technologyName: item.technologyName,
      totalCount: item.totalCount,
      color: chartColors[index % chartColors.length],
    }));
  };

  // 渲染图表
  const renderChart = () => {
    if (!chartData.value.length) return;

    const formValues = getFieldsValue();
    const { startYear, endYear } = formValues;

    // 生成年份数组
    const years: number[] = [];
    for (let year = startYear; year <= endYear; year++) {
      years.push(year);
    }

    // 生成系列数据
    const series: ChartSeries[] = chartData.value.map((item, index) => {
      const data = years.map((year) => {
        const yearData = item.yearDataList.find((d) => d.year === year);
        return yearData ? yearData.count : 0;
      });

      return {
        name: item.technologyName,
        type: currentChartType.value === 'mixed' ? (index % 2 === 0 ? 'bar' : 'line') : currentChartType.value,
        data,
        smooth: currentChartType.value === 'line',
        itemStyle: {
          color: chartColors[index % chartColors.length],
        },
        lineStyle:
          currentChartType.value === 'line'
            ? {
                width: 3,
              }
            : undefined,
      };
    });

    const option: EChartsOption = {
      title: {
        text: '专利申请趋势分析',
        left: 'center',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: function (params: any) {
          let html = `<div><strong>${params[0].axisValue}年</strong></div>`;
          params.forEach((param: any) => {
            html += `<div style="margin: 2px 0;">
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${param.color}"></span>
            ${param.seriesName}: <strong>${param.value}</strong> 件
          </div>`;
          });
          return html;
        },
      },
      legend: {
        top: '10%',
        type: 'scroll',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '20%',
        containLabel: true,
      },
      toolbox: {
        feature: {
          saveAsImage: {
            title: '保存图片',
            name: '专利申请趋势图',
          },
          dataZoom: {
            title: {
              zoom: '区域缩放',
              back: '区域缩放还原',
            },
          },
          restore: { title: '还原' },
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: currentChartType.value === 'bar',
        data: years,
        name: '年份',
        nameLocation: 'middle',
        nameGap: 30,
      },
      yAxis: {
        type: 'value',
        name: '专利数量（件）',
        nameLocation: 'middle',
        nameGap: 50,
        minInterval: 1,
      },
      series: series as any,
      dataZoom: [
        {
          type: 'slider',
          show: years.length > 10,
          xAxisIndex: 0,
          start: 0,
          end: 100,
        },
      ],
    };

    setChartOptions(option);
  };

  // 重置表单
  const handleReset = () => {
    // BasicForm 会自动重置表单字段到默认值
    chartData.value = [];
    statisticsData.value = [];
    currentChartType.value = 'line';

    const chartInstance = getChartInstance();
    if (chartInstance) {
      chartInstance.clear();
    }
  };

  // 页面初始化
  onMounted(() => {
    // ApiTreeSelect 组件会自动加载技术分类数据，无需手动调用
  });
</script>

<style scoped lang="less">
  .chart-container {
    width: 100%;
    margin-bottom: 24px;
  }

  .statistics {
    margin-top: 24px;
    padding: 20px;
    background: #fafafa;
    border-radius: 6px;

    .ant-statistic {
      text-align: center;
    }
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }

  :deep(.ant-select-selector) {
    min-height: 32px;
  }

  :deep(.ant-radio-button-wrapper) {
    height: 32px;
    line-height: 30px;
  }
</style>
